<template>
  <div class="upload-container">
    <span title="文件管理" @click="dialogVisible=true">
      <i class="el-icon-files" style="font-size: 20px;" />
    </span>

    <el-drawer
      :visible.sync="dialogVisible"
      :size="size"
      append-to-body
      title="文件管理"
      :wrapper-closable="false"
      :close-on-click-modal="false"
    >
      <div class="drawer-content">
        <el-tabs v-model="activeName" :value="'second'">
          <!-- 文件上传标签页 -->
          <el-tab-pane label="文件上传" name="second">
            <div class="upload-layout">
              <!-- 左侧目录选择区域 -->
              <div class="directory-section">
                <h4>选择上传目录</h4>
                <crmdirectoryselector
                  :id="selected_directory"
                  :name="selected_directory__name"
                  @change="handleDirectoryChange"
                />

                <el-alert
                  v-if="selected_directory__name === null"
                  title="请选择目录后再上传文件"
                  type="warning"
                  :closable="false"
                  class="mt-3"
                />

                <el-alert
                  v-else
                  :title="'当前目录: ' + selected_directory__name"
                  type="success"
                  :closable="false"
                  class="mt-3"
                />
              </div>

              <!-- 右侧上传区域 -->
              <div class="upload-section">
                <!-- 上传选项配置 -->
                <div class="upload-options">
                  <el-input
                    v-model="combin_search_keyword"
                    placeholder="输入关键词方便后续搜索"
                    class="mb-3"
                  />

                  <div class="upload-controls">
                    <el-select
                      v-model="acl_type"
                      placeholder="访问权限"
                      size="small"
                      class="access-select"
                    >
                      <el-option label="7天临时链接" value="7" />
                      <el-option label="3天临时链接" value="3" />
                      <el-option label="公开链接" value="public_read" />
                    </el-select>
                  </div>

                  <el-alert
                    type="info"
                    class="mb-3"
                  >
                    文件有效期说明：文章用图请用永久链接，重要文件请使用临时链接以防泄露
                  </el-alert>
                </div>

                <!-- 上传区域 -->
                <el-tabs v-model="uploadType" class="upload-tabs">
                  <el-tab-pane label="本地文件" name="local">
                    <el-upload
                      v-if="selected_directory !== null"
                      ref="upload"
                      :headers="headers"
                      :action="upload_url"
                      :multiple="true"
                      drag
                      :auto-upload="false"
                      :file-list="fileList"
                      :show-file-list="true"
                      :before-upload="beforeUpload"
                      :data="uploadData"
                      :on-remove="handleRemove"
                      :on-success="handleSuccess"
                      class="upload-area"
                    >
                      <i class="el-icon-upload" />
                      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                      <div class="el-upload__tip">过大文件请使用网盘</div>
                    </el-upload>

                    <el-button
                      v-if="selected_directory__name !== null"
                      type="primary"
                      size="small"
                      class="mt-3"
                      @click="submitUpload"
                    >
                      上传到服务器
                    </el-button>
                  </el-tab-pane>

                  <el-tab-pane label="粘贴图片" name="paste">
                    <div
                      v-if="selected_directory !== null"
                      class="paste-area"
                      contenteditable="true"
                      placeholder="在此处粘贴图片"
                      @paste="handlePaste"
                    >
                      在此处粘贴图片
                    </div>
                    <el-button
                      v-if="selected_directory__name !== null"
                      type="primary"
                      class="mt-3"
                      @click="submitImage"
                    >
                      提交图片
                    </el-button>
                  </el-tab-pane>
                </el-tabs>
              </div>

              <!-- 上传结果列表 -->
              <div v-if="success_data.length" class="result-section">
                <h4>已上传文件</h4>
                <el-card class="uploaded-files">
                  <ul>
                    <li v-for="(item,index) in success_data" :key="index" class="upload-item">
                      <el-link type="success" :href="item.url" target="_blank">
                        {{ item.filename }}
                      </el-link>
                      <el-button
                        type="primary"
                        size="small"
                        icon="el-icon-circle-plus"
                        @click="handleInsertFile(item)"
                      >
                        插入
                      </el-button>
                    </li>
                  </ul>
                </el-card>
              </div>
            </div>
          </el-tab-pane>

          <!-- 浏览附件标签页 -->
          <el-tab-pane label="浏览附件" name="first">
            <el-row>
              <el-col :xs="24" :sm="6" :md="6" :lg="6" :xl="6">
                <el-row>
                  <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                    <crmdirectoryselector
                      :id="search_directory_id"
                      :name="selected_directory__name"
                      @change="handleChangeSearchDirectory"
                    />
                  </el-col>
                  <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                    <el-button icon="el-icon-refresh" @click="handleGetFiles" />
                  </el-col>
                </el-row>
              </el-col>
              <el-col :xs="24" :sm="18" :md="18" :lg="18" :xl="18">
                <el-table
                  v-loading="listLoading"
                  :data="files"
                  class="my-custom-table"
                  :show-header="false"
                  fit
                  highlight-current-row
                >
                  <el-table-column type="selection" width="55" />
                  <el-table-column align="left" width="200" prop="url" label="缩略图">
                    <template slot-scope="scope">
                      <el-image
                        v-if="scope.row.content_type.indexOf('image') !== -1"
                        :src="scope.row.url"
                        :preview-src-list="[scope.row.url]"
                        style="height: 100px; width: 100px"
                      />
                      <a
                        v-else-if="scope.row.filename.indexOf('pdf') !== -1"
                        :href="scope.row.url"
                        target="_blank"
                      >
                        <svg-icon style="height: 100px; width: 100px" icon-class="pdf" />
                      </a>
                      <a
                        v-else-if="scope.row.filename.indexOf('xlsx') !== -1"
                        :href="scope.row.url"
                        target="_blank"
                      >
                        <svg-icon style="height: 100px; width: 100px" icon-class="xlsx" />
                      </a>
                      <a
                        v-else-if="scope.row.filename.indexOf('xls') !== -1"
                        :href="scope.row.url"
                        target="_blank"
                      >
                        <svg-icon style="height: 100px; width: 100px" icon-class="xls" />
                      </a>
                      <a
                        v-else-if="scope.row.filename.indexOf('zip') !== -1"
                        :href="scope.row.url"
                        target="_blank"
                      >
                        <svg-icon style="height: 100px; width: 100px" icon-class="zip" />
                      </a>
                      <a
                        v-else
                        :href="scope.row.url"
                        target="_blank"
                        style="height: 100px; width: 100px"
                      >
                        <svg-icon icon-class="document" />
                      </a>
                    </template>
                  </el-table-column>
                  <el-table-column align="left" label="存放" prop="save_in" />
                  <el-table-column align="left" label="filename" prop="filename">
                    <template slot-scope="scope">
                      <a :href="scope.row.url" target="_blank">{{ scope.row.filename }}</a>
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="操作" width="300">
                    <template slot-scope="scope">
                      <el-button
                        v-if="scope.row.filename.indexOf('xlsx') !== -1"
                        size="mini"
                        type="primary"
                        icon="el-icon-set-up"
                        title="点击翻译文档"
                        @click="handleTranslate(scope.row)"
                      >
                        翻译
                      </el-button>
                      <el-button
                        size="mini"
                        type="danger"
                        icon="el-icon-delete"
                        :loading="operateloading"
                        @click="handleDeleteFile(scope.row)"
                      >
                        删除
                      </el-button>
                      <el-button
                        type="success"
                        size="mini"
                        icon="el-icon-circle-plus"
                        @click="handleInsertFile(scope.row)"
                      >
                        插入
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <el-pagination
                  v-if="files.length"
                  background
                  class="mt-pagination"
                  :current-page="page"
                  :page-sizes="[10,20,50,100]"
                  :page-size="pagesize"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="total"
                  @size-change="handleSizeChange"
                  @current-change="handlePageChange"
                />
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-drawer>

    <!-- 翻译对话框 -->
    <el-dialog
      :visible.sync="translateBoxVisible"
      append-to-body
      title="翻译文件"
    >
      <el-form>
        <el-form-item label="源语言">
          <el-select v-model="current_item.source_language" placeholder="请选择">
            <el-option
              v-for="item in languages"
              :key="item.code"
              :label="item.label"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="目标语言">
          <el-select v-model="current_item.target_language" placeholder="请选择">
            <el-option
              v-for="item in languages"
              :key="item.code"
              :label="item.label"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <el-alert>翻译结果会作为新文件插入到文件管理，并钉钉通知到工作群</el-alert>
      <span slot="footer">
        <el-button @click="translateBoxVisible = false">关闭</el-button>
        <el-button
          size="mini"
          type="primary"
          @click="handletranslateFile"
        >
          翻译
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import Crmdirectoryselector from '../../views/crm/elements/crmdirectoryselector'
import { Get as GetFile, Delete, Uploadtempfile, translatefile } from '@/api/crm/crmfile'
import qs from 'qs'
import { languages } from '../../api/crm/crmcommon'

export default {
  name: 'Crmfilesmanager',
  components: {
    Crmdirectoryselector
  },

  props: {
    color: {
      type: String,
      default: '#1890ff'
    },
    size: {
      type: String,
      default: '80%'
    }
  },

  data() {
    return {
      // 翻译相关
      translateBoxVisible: false,
      current_item: {
        id: '',
        url: '',
        filename: '',
        source_language: 'en',
        target_language: 'zh'
      },
      languages: languages,

      // 上传相关
      uploadType: 'local',
      operateloading: false,
      listLoading: false,
      activeName: 'second', // 默认显示上传标签页
      dialogVisible: false,
      listObj: {},
      fileList: [],
      upload_url: '',
      pastedImage: '',
      uploadTarget: 'cloud',
      success_data: [],
      boolUploadSucceed: false,
      combin_search_keyword: '',
      selected_directory: null,
      acl_type: '7',
      search_directory_id: '',
      selected_directory__name: null,

      // 文件列表相关
      files: [],
      order_by: 'create_at',
      order_desc: 1,
      pagesize: 20,
      page: 1,
      total: 0
    }
  },

  computed: {
    headers() {
      return {
        'Authorization': getToken()
      }
    },

    // 上传数据
    uploadData() {
      return {
        directory_id: this.selected_directory || -1,
        acl_type: this.acl_type,
        search_term: this.combin_search_keyword,
        project_id: this.$store.getters.projectId
      }
    }
  },

  mounted() {
    this.boolUploadSucceed = false
    this.upload_url = process.env.VUE_APP_BASE_API + '/crm/api/crmfile/'
  },

  methods: {
    // 目录选择相关方法
    handleDirectoryChange(data) {
      this.selected_directory = data.id
      this.selected_directory__name = data.name
    },

    handleChangeSearchDirectory(data) {
      if (data) {
        this.search_directory_id = data.id
        this.handleGetFiles()
      } else {
        this.handleGetFiles()
      }
    },

    // 文件获取和操作方法
    handleGetFiles() {
      this.listLoading = true
      GetFile(null, qs.stringify({
        kw: this.kwInput,
        directory_id: this.search_directory_id,
        pagesize: this.pagesize,
        page: this.page,
        order_by: this.order_by,
        order_desc: this.order_desc
      }))
        .then(response => {
          this.files = response.data.data
          this.total = response.data.total
          this.listLoading = false
        })
        .catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },

    // 文件删除方法
    handleDeleteFile(item) {
      this.operateloading = true
      Delete(item.id).then(() => {
        this.$notify({
          title: '成功',
          message: '文件删除成功',
          type: 'success',
          duration: 2000
        })
        this.handleGetFiles()
        this.operateloading = false
      })
    },

    // 翻译相关方法
    handleTranslate(item) {
      this.translateBoxVisible = true
      this.current_item = {
        ...this.current_item,
        filename: item.filename,
        url: item.url,
        id: item.id
      }
    },

    handletranslateFile() {
      translatefile(this.current_item).then(() => {
        this.$message.success('添加翻译成功,请等待翻译结果')
        this.translateBoxVisible = false
      })
    },

    // 上传相关方法
    submitUpload() {
      if (!this.selected_directory) {
        this.$message.warning('请先选择上传目录')
        return
      }
      this.$refs.upload.submit()
    },

    handleSuccess(response, file) {
      if (response.success) {
        this.$notify({
          title: '成功',
          message: `文件${file.name}上传成功`,
          type: 'success',
          duration: 2000
        })

        const uid = file.uid
        const objKeyArr = Object.keys(this.listObj)
        for (let i = 0; i < objKeyArr.length; i++) {
          if (this.listObj[objKeyArr[i]].uid === uid) {
            this.listObj[objKeyArr[i]].url = response.data.url
            this.success_data.push(response.data)
            this.listObj[objKeyArr[i]].hasSuccess = true
            return
          }
        }
      } else {
        this.$notify({
          title: '失败',
          message: `文件${file.name}上传失败, ${response.msg}`,
          type: 'error',
          duration: 3000
        })
      }
    },

    // 文件移除方法
    handleRemove(file) {
      const uid = file.uid
      const objKeyArr = Object.keys(this.listObj)
      for (let i = 0; i < objKeyArr.length; i++) {
        if (this.listObj[objKeyArr[i]].uid === uid) {
          delete this.listObj[objKeyArr[i]]
          return
        }
      }
    },

    // 上传前检查
    beforeUpload(file) {
      const _self = this
      const fileName = file.uid
      this.listObj[fileName] = {}
      return new Promise((resolve) => {
        _self.listObj[fileName] = { hasSuccess: false, uid: file.uid }
        resolve(true)
      })
    },

    // 图片粘贴处理
    handlePaste(event) {
      const items = (event.clipboardData || event.originalEvent.clipboardData).items
      for (const index in items) {
        const item = items[index]
        if (item.kind === 'file') {
          const blob = item.getAsFile()
          const reader = new FileReader()
          reader.onload = (e) => {
            this.pastedImage = e.target.result
          }
          reader.readAsDataURL(blob)
        }
      }
    },

    // 粘贴图片提交
    submitImage() {
      if (!this.pastedImage) {
        this.$message.error('没有检测到粘贴的图片')
        return
      }

      Uploadtempfile({ file_data: this.pastedImage }).then(response => {
        this.$message.success('图片已保存到本地')
        const filename = response.url.split('/').pop()
        this.success_data.push({ url: response.url, filename: filename })
        this.handleInsertFile({ url: response.url, filename: filename })
      })
    },

    // 文件插入方法
    handleInsertFile(item) {
      this.$emit('insert', item)
      this.dialogVisible = false
    },

    // 分页方法
    handleSizeChange(val) {
      this.pagesize = val
      this.handleGetFiles()
    },

    handlePageChange(val) {
      this.page = val
      this.handleGetFiles()
    }
  }
}
</script>

<style lang="scss" scoped>
.drawer-content {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.upload-layout {
  display: grid;
  grid-template-columns: 250px 1fr;
  gap: 20px;
  height: calc(100vh - 200px);
  position: relative;
}

.directory-section {
  padding: 15px;
  border-right: 1px solid #eee;
  background-color: #fafafa;
  border-radius: 4px;

  h4 {
    margin-bottom: 15px;
    color: #606266;
    font-weight: 500;
  }
}

.upload-section {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 15px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.upload-options {
  .upload-controls {
    display: flex;
    gap: 10px;
    margin-bottom: 15px;
    align-items: center;
  }

  .access-select {
    width: 200px;
  }
}

.upload-tabs {
  flex: 1;

  .upload-area {
    width: 100%;

    :deep(.el-upload-dragger) {
      width: 100%;
      height: 200px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;

      &:hover {
        border-color: #409EFF;
      }

      i {
        font-size: 48px;
        color: #409EFF;
        margin-bottom: 10px;
      }
    }
  }
}

.paste-area {
  border: 1px dashed #ccc;
  padding: 15px;
  min-height: 200px;
  margin-bottom: 15px;
  background: #fafafa;
  border-radius: 4px;
  transition: all 0.3s;

  &:focus {
    outline: none;
    border-color: #409EFF;
    background: #fff;
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
  }

  &::placeholder {
    color: #909399;
  }
}

.result-section {
  position: fixed;
  right: 20px;
  top: 100px;
  width: 300px;
  max-height: calc(100vh - 200px);
  overflow-y: auto;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

  h4 {
    padding: 15px;
    margin: 0;
    border-bottom: 1px solid #eee;
    color: #606266;
    font-weight: 500;
  }

  .uploaded-files {
    border: none;

    ul {
      list-style: none;
      padding: 0;
      margin: 0;
    }

    .upload-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px 15px;
      transition: background-color 0.3s;

      &:hover {
        background-color: #f5f7fa;
      }

      &:not(:last-child) {
        border-bottom: 1px solid #eee;
      }

      .el-link {
        flex: 1;
        margin-right: 10px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }
}

.my-custom-table {
  max-height: 80vh;
  overflow-y: auto;
}

.mt-pagination {
  margin-top: 15px;
  text-align: right;
}

// 辅助类
.mt-3 {
  margin-top: 12px;
}

.mb-3 {
  margin-bottom: 12px;
}

// 响应式调整
@media screen and (max-width: 1200px) {
  .upload-layout {
    grid-template-columns: 1fr;
  }

  .directory-section {
    border-right: none;
    border-bottom: 1px solid #eee;
  }

  .result-section {
    position: static;
    width: 100%;
    max-height: none;
    margin-top: 20px;
  }
}
</style>
